using UnityEngine;
using QFramework;
using System.Collections.Generic;
using System;

namespace survivor
{
    [Serializable]
    public class EnemyWave
    {
        public float GenerateDuration = 1;
        public Enemy EnemyPrefab;
        public int Seconds = 10;
    }

	public partial class EnemyGenerator : ViewController
	{
		private float mCurrentGenerateSeconds = 0;
        private float mCurrentWaveSeconds = 0;

        public static BindableProperty<int> EnemyCount = new BindableProperty<int>(0);

        [SerializeField]
        public List<EnemyWave> EnemyWaves = new List<EnemyWave>();

        private Queue<EnemyWave> mEnemyWavesQueue = new Queue<EnemyWave>();

        public EnemyWave CurrentWave => mCurrentWave;

        public int WaveCount = 0;
        public bool LastWave => WaveCount == EnemyWaves.Count;

        private void Start()
        {
            foreach (var enemyWave in EnemyWaves)
            {
                mEnemyWavesQueue.Enqueue(enemyWave);
            }
        }

        private EnemyWave mCurrentWave = null;

        private void Update()
        {
            if (mCurrentWave == null)
            {
                if (mEnemyWavesQueue.Count > 0)
                {
                    WaveCount++;
                    mCurrentWave = mEnemyWavesQueue.Dequeue();
                    mCurrentGenerateSeconds = 0;
                    mCurrentWaveSeconds = 0;
                }
            }

            if (mCurrentWave != null)
            {
                mCurrentGenerateSeconds += Time.deltaTime;
                mCurrentWaveSeconds += Time.deltaTime;

                if (mCurrentGenerateSeconds >= mCurrentWave.GenerateDuration)
                {
                    mCurrentGenerateSeconds = 0;

                    var player = Player.ins;
                    if (player)
                    {
                        var randomAngle = UnityEngine.Random.Range(0, 360f);
                        var randomRadius = randomAngle * Mathf.Deg2Rad;
                        var direction = new Vector3(Mathf.Cos(randomRadius), Mathf.Sin(randomRadius));
                        var generatePos = player.transform.position + direction * 10;

                        mCurrentWave.EnemyPrefab.Instantiate().Position(generatePos).Show();
                    }
                }
            }

            if (mCurrentWaveSeconds >= mCurrentWave.Seconds)
            {
                mCurrentWave = null;
            }
        }
    }
}
